package com.wuster.utils;

import com.auth0.jwt.JWT;

import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.Data;
import org.springframework.stereotype.Component;


import java.util.HashMap;
import java.util.Map;

@Component
@Data
public class JwtUtil {

    private String secretKey;

    /**
     * 加密token.  设置每个token的有效期为5天
     */
    public String getToken(String userId, String userRole) {
        //这个是放到负载payLoad 里面,魔法值可以使用常量类进行封装.
        String token = JWT
                .create()
                .withClaim("userId" ,userId) //登录用户的id
                .withClaim("userRole", userRole)  //登录用户的角色
                .withClaim("expiration", System.currentTimeMillis() + 1000*60*60*24*5)  //到期时间
                .sign(Algorithm.HMAC256(secretKey));  //头部信息 第一个参数为加密方式为哈希512  第二个参数为加的盐为secret字符串
        return token;
    }


    /**
     * 解析token.
     * {
     * "userId": "weizhong",
     * "userRole": "ROLE_ADMIN",
     * "timeStamp": "134143214"
     * }
     */
    public Map<String, String> parseToken(String token) {
        HashMap<String, String> map = new HashMap<String, String>();
        DecodedJWT decodedjwt = JWT.require(Algorithm.HMAC256(secretKey))
                .build().verify(token);
        Claim userId = decodedjwt.getClaim("userId");
        Claim userRole = decodedjwt.getClaim("userRole");
        Claim expiration = decodedjwt.getClaim("expiration");
        map.put("userId", userId.asString());
        map.put("userRole", userRole.asString());
        map.put("expiration", expiration.asLong().toString());
        return map;
    }

}
